import React, { Component } from 'react';
import { Button, Table, Icon, message, Popconfirm, Dropdown, Menu, Input, Tooltip } from 'antd';
import { delStaff } from '@api/organization';
import BatchUploadStaffModal from '../../components/batch-upload-staff-modal';
import PropTypes from 'prop-types';
import { NavLink } from 'react-router-dom';
import _ from 'lodash';
import './index.less';
const Search = Input.Search;
const ClsPrefix = 'org-staff-list';

const columns = context => [
  {
    title: '姓名',
    dataIndex: 'nickname'
  },
  {
    title: '部门',
    dataIndex: 'parentOrgPath',
    render: data => data.join('/')
  },
  {
    title: '手机号码',
    dataIndex: 'telephone'
  },
  {
    title: '邮箱',
    dataIndex: 'email'
  },
  {
    title: '用户角色',
    dataIndex: 'roleInfo',
    className: 'userRole',
    // eslint-disable-next-line react/display-name
    render: (key, row) => {
      if (!key) {
        // eslint-disable-next-line no-param-reassign
        key = { name: '未开通' };
      }
      let toopDict = {
        未开通: '人员还不是系统用户，点击后可为其进行用户创建',
        安全管理员: '该人员已为系统用户，用户角色为安全管理员。点击后可进行用户编辑',
        安全操作员: '该人员已为系统用户，用户角色为安全操作员。点击后可进行用户编辑。'
        // 4: '该人员已为系统用户，用户角色为普通用户。点击后可进行用户编辑。'
      };
      return (
        <Tooltip placement="top" title={toopDict[key.name]}>
          <NavLink to={`/asset-config/user-manage?id=${row._id}`} style={{ cursor: 'pointer' }}>
            {key.name}
          </NavLink>
        </Tooltip>
      );
    },
    filters: [
      { text: '未开通', value: '未开通' },
      { text: '安全管理员', value: '安全管理员' }
      // { text: '安全操作员', value: '安全操作员' }
    ],
    filterMultiple: false,
    filteredValue:
      context.props.staffFilter.role && context.props.staffFilter.role.length !== 0
        ? context.props.staffFilter.role
        : []
  },
  {
    title: '操作',
    render: row => {
      return (
        <div>
          <Icon
            type="form"
            style={{ marginRight: 10, cursor: 'pointer' }}
            onClick={() => {
              context.props.onEditRowChange(row);
              context.props.showAddStaffModal();
            }}
          />
          <Popconfirm
            title="确认删除该人员信息吗?"
            onConfirm={() => context.handleDelStaff([row._id])}
          >
            <Icon type="delete" style={{ cursor: 'pointer' }} />
          </Popconfirm>
        </div>
      );
    }
  }
];

const rowSelection = context => ({
  selectedRowKeys: context.state.selectedRowKeys,
  onChange: (selectedRowKeys, selectedRows) => {
    context.setState({ selectedRows, selectedRowKeys });
  }
});

const pagination = (staffFilter, total) => ({
  current: staffFilter.page || 1,
  pageSize: staffFilter.pageSize || 10,
  total: total,
  showTotal: num => `共 ${num} 条`,
  size: 'small'
});

class StaffList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      tableScrollY: 0,
      selectedRowKeys: [],
      selectedRows: [],
      batchStaffVisable: false
    };
  }

  static propTypes = {
    loadStaffList: PropTypes.func,
    loadOrganizationCascaderTree: PropTypes.func,
    onBatchEditStaffIdsChange: PropTypes.func,
    showAddStaffModal: PropTypes.func,
    staffList: PropTypes.array,
    staffFilter: PropTypes.object,
    total: PropTypes.number,
    onTableChange: PropTypes.func,
    onSearch: PropTypes.func,
    SearchOnChange: PropTypes.func,
    history: PropTypes.object
  };
  componentDidMount() {
    const { history, showAddStaffModal } = this.props;
    if (history.location.search === '?openModel') {
      showAddStaffModal();
    }
    this.changeScrollY();
    window.onresize = () => {
      this.changeScrollY();
    };
  }
  changeScrollY = () => {
    const height = document.querySelector('.content-wrapper').clientHeight;
    this.setState({ tableScrollY: height - 258 });
  };
  handleDelStaff = (staffIds, clearKeys = false) => {
    delStaff({ staffIds }).then(rs => {
      _.get(rs, 'data.result', false) && message.success('删除员工成功!');
      clearKeys && this.setState({ selectedRows: [], selectedRowKeys: [] });
      this.props.loadStaffList();
      this.props.loadOrganizationCascaderTree();
    });
  };

  handleEditStaffmult = () => {
    const { selectedRows } = this.state;
    const staffIds = [...selectedRows.map(item => item._id)];
    this.props.onBatchEditStaffIdsChange(staffIds);
    this.props.showAddStaffModal();
  };

  closeBatchAddStaffModal = () => {
    this.setState({ batchStaffVisable: false });
  };

  render() {
    const { selectedRows, batchStaffVisable, tableScrollY } = this.state;
    const { loadStaffList, loadOrganizationCascaderTree, onSearch, SearchOnChange } = this.props;
    const { staffList, staffFilter, total, onTableChange, showAddStaffModal } = this.props;
    return (
      <div className={`${ClsPrefix}`}>
        <div className={`${ClsPrefix}-btn-box`}>
          <Dropdown
            overlay={() => (
              <Menu>
                <Menu.Item onClick={() => showAddStaffModal()}>人工添加人员</Menu.Item>
                <Menu.Item onClick={() => this.setState({ batchStaffVisable: true })}>
                  批量添加人员
                </Menu.Item>
              </Menu>
            )}
          >
            <Button icon="plus" type="primary" style={{ marginRight: 10 }}>
              添加人员
            </Button>
          </Dropdown>
          <Button
            style={{ marginRight: 10 }}
            disabled={!(selectedRows.length && selectedRows.length > 0)}
            onClick={() => this.handleEditStaffmult()}
          >
            编辑
          </Button>
          <Popconfirm
            title="确认删除勾选的人员信息吗?"
            onConfirm={() => this.handleDelStaff([...selectedRows.map(item => item._id)], true)}
            disabled={!selectedRows.length}
          >
            <Button type="danger" disabled={!selectedRows.length} okText="确定" cancelText="取消">
              删除
            </Button>
          </Popconfirm>
          <div className="search">
            <Search
              value={staffFilter.search}
              onChange={e => SearchOnChange(e.target.value)}
              onSearch={onSearch}
              enterButton
              placeholder="请输入人员关键词搜索"
            />
          </div>
        </div>
        <div className={`${ClsPrefix}-table-wrapper`}>
          <Table
            columns={columns(this)}
            dataSource={staffList}
            rowSelection={rowSelection(this)}
            scroll={{ y: tableScrollY }}
            pagination={pagination(staffFilter, total)}
            onChange={onTableChange}
          />
        </div>
        <BatchUploadStaffModal
          visible={batchStaffVisable}
          onClose={this.closeBatchAddStaffModal}
          loadStaffList={loadStaffList}
          loadOrganizationCascaderTree={loadOrganizationCascaderTree}
        />
      </div>
    );
  }
}

export default StaffList;
